﻿using System;
using System.Runtime.CompilerServices;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;

namespace Smart.Model
{
    /// <summary>
    /// 用于async await适配
    /// </summary>
    [ILAdapter]
    public class IAsyncStateMachineClassInheritanceAdaptor : CrossBindingAdaptor
    {
        public override Type BaseCLRType
        {
            get
            {
                return typeof(IAsyncStateMachine);
            }
        }

        public override Type AdaptorType
        {
            get
            {
                return typeof(Adaptor);
            }
        }

        public override object CreateCLRInstance(ILRuntime.Runtime.Enviorment.AppDomain appdomain, ILTypeInstance instance)
        {
            return new Adaptor(appdomain, instance);
        }

        public class Adaptor : MyAdaptor, IAsyncStateMachine
        {
            public Adaptor(ILRuntime.Runtime.Enviorment.AppDomain appDomain, ILTypeInstance instance) : base(appDomain, instance)
            {

            }

            protected override AdaptHelper.AdaptMethod[] GetAdaptMethods()
            {
                AdaptHelper.AdaptMethod[] methods =
                {
                    new AdaptHelper.AdaptMethod { Name = "MoveNext", ParamCount = 0 },
                    new AdaptHelper.AdaptMethod { Name = "SetStateMachine", ParamCount = 1 },
                };
                return methods;
            }

            public void MoveNext()
            {
                Invoke(0);
            }

            public void SetStateMachine(IAsyncStateMachine stateMachine)
            {
                Invoke(1, stateMachine);
            }
        }
    }
}
